package com.dj.mingkong.admin.biz.service.system.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dj.mingkong.admin.biz.controller.system.vo.request.DictionaryAddVo;
import com.dj.mingkong.admin.biz.controller.system.vo.request.DictionaryQueryVo;
import com.dj.mingkong.admin.biz.controller.system.vo.request.DictionaryUpdateVo;
import com.dj.mingkong.admin.biz.controller.system.vo.response.DictionaryVo;
import com.dj.mingkong.admin.biz.repository.database.system.DictionaryRepository;
import com.dj.mingkong.admin.biz.service.system.DictionaryService;
import com.dj.mingkong.common.constant.CommonConstants;
import com.dj.mingkong.common.exception.ValidateException;
import com.dj.mingkong.common.infrastructure.base.dto.delete.DeleteVo;
import com.dj.mingkong.common.infrastructure.base.dto.page.PageVo;
import com.dj.mingkong.common.infrastructure.eo.database.system.DictionaryEo;
import com.dj.mingkong.common.util.AssertUtils;
import com.dj.mingkong.common.util.SmartBeanCopy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * 数据字典服务实现类
 *
 * @author zenglonghui
 * @date: 2022/7/12 17:48
 */
@Slf4j
@Service("dictionaryService")
public class DictionaryServiceImpl implements DictionaryService {
    @Resource
    private DictionaryRepository dictionaryRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(DictionaryAddVo addVo) {
        final DictionaryEo dictionaryEo = SmartBeanCopy.copy(addVo, DictionaryEo.class);
        if (!CommonConstants.DEFAULT_ID.equals(addVo.getParentId())) {
            final DictionaryEo parentEo = dictionaryRepository.getById(addVo.getParentId());
            AssertUtils.isNotNull(parentEo, "parentId invalid");
            dictionaryEo.setFullKey(parentEo.getFullKey().concat(CommonConstants.FULL_KEY_JOIN).concat(dictionaryEo.getDictKey()));
        } else {
            dictionaryEo.setFullKey(dictionaryEo.getDictKey());
        }
        if (dictionaryRepository.existByFullKey(dictionaryEo.getFullKey())) {
            throw new ValidateException("fullKey already exist");
        }
        dictionaryRepository.save(dictionaryEo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateById(DictionaryUpdateVo updateVo) {
        final DictionaryEo dictionaryEo = SmartBeanCopy.copy(updateVo, DictionaryEo.class);
        dictionaryRepository.updateById(dictionaryEo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(DeleteVo deleteVo) {
        dictionaryRepository.deleteById(deleteVo.getId());
    }

    @Override
    public PageVo<DictionaryVo> pageByVo(DictionaryQueryVo queryVo) {
        final DictionaryEo dictionaryEo = SmartBeanCopy.copy(queryVo, DictionaryEo.class);
        final Page<DictionaryEo> eoPage = dictionaryRepository.listPage(dictionaryEo,
                queryVo.getPage(), queryVo.getPageSize());
        return SmartBeanCopy.copyPageVo(eoPage, DictionaryVo.class);
    }

    @Override
    public List<DictionaryVo> getByParentKey(String key) {
        final Optional<DictionaryEo> eoOptional = dictionaryRepository.oneOptByDictKey(key);
        if (eoOptional.isEmpty()) {
            return Collections.emptyList();
        }
        final List<DictionaryEo> dictionaryEos = dictionaryRepository.listByParentId(eoOptional.get().getId());
        return SmartBeanCopy.copy(dictionaryEos, DictionaryVo.class);
    }

    @Override
    public List<DictionaryVo> listTree() {
        final List<DictionaryEo> allEos = dictionaryRepository.lambdaQuery().orderByAsc(DictionaryEo::getSort).list();
        if (CollectionUtils.isEmpty(allEos)) {
            return Collections.emptyList();
        }
        final List<DictionaryVo> allVos = SmartBeanCopy.copy(allEos, DictionaryVo.class);
        final List<DictionaryVo> vos = allVos.stream().filter(vo ->
                CommonConstants.DEFAULT_ID.equals(vo.getParentId())).toList();
        setChildren(vos, allVos);
        return vos;
    }

    private void setChildren(List<DictionaryVo> vos, List<DictionaryVo> allVos) {
        vos.forEach(vo -> {
            final List<DictionaryVo> childrenList = allVos.stream().filter(item ->
                    vo.getId().equals(item.getParentId())).toList();
            vo.setChildren(childrenList);
            if (CollectionUtils.isNotEmpty(childrenList)) {
                setChildren(childrenList, allVos);
            }
        });
    }

}
